package com.github.pig.common.bean.aop;

import java.lang.reflect.Method;
import java.util.Base64;
import javax.servlet.http.HttpServletRequest;

import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.constant.SecurityConstants;
import com.github.pig.common.util.UserUtils;
import com.xiaoleilu.hutool.util.StrUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class SystemLogAspect {
    // 本地异常日志记录对象
    private static final Logger logger = Logger.getLogger(SystemLogAspect.class);

    ThreadLocal<Long> startTime = new ThreadLocal<Long>();

    // Controller层切点
    @Pointcut("execution(* com..controller..*Controller.*(..)) || @annotation(com.github.pig.common.bean.aop.SystemControllerLog) ")
    public void controllerAspect() {
    }
    /**
     * 前置通知 用于拦截Controller层记录用户的操作
     *
     * @param joinPoint 切点
     */
    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes()).getRequest();
            String username = request.getHeader(SecurityConstants.USER_HEADER);
            // 请求的IP
            String ip = request.getRemoteAddr();
            String params = "";
            if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
                for (int i = 0; i < joinPoint.getArgs().length; i++) {
                    params += joinPoint.getArgs()[i] + ";";
                }
            }

            String name = joinPoint.getTarget().getClass().getName();
            //菜单和字典不打印
            if(name.contains("MenuController") || name.contains("DictController")){
                return ;
            }
            // *========控制台输出=========*//
            logger.info("=====前置通知开始=====");
            logger.info("请求方法:"
                    + (joinPoint.getTarget().getClass().getName() + "."
                    + joinPoint.getSignature().getName() + "()"));
            //不展示上传文件的参数
            if(!joinPoint.getSignature().getName().contains("upload")){
                logger.info("请求参数:" + params);
            }
            logger.info("请求人:" +username);
            logger.info("请求IP:" + ip);
            logger.info("=====前置通知结束=====");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("==前置通知异常==");
            logger.error("异常信息:{" + e.getMessage() + "}");
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param joinPoint 切点
     * @return 方法描述
     * @throws Exception
     */
    public static String getControllerMethodDescription(JoinPoint joinPoint)
            throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description = method.getAnnotation(
                            SystemControllerLog.class).description();
                    break;
                }
            }
        }
        return description;
    }
}
